//
//  ZZFContentTextView.m
//  YYUDemo
//
//  Created by zsp on 2017/3/17.
//  Copyright © 2017年 zsp. All rights reserved.
//

#import "ZZFContentTextView.h"
#import <Masonry.h>

#import "ZZFConfigSet.h"
#import "UIColor+ZZFExtend.h"

@interface ZZFContentTextView ()<UITextViewDelegate>

@property(nonatomic, copy)NSString* placeHolderStr;
@property(nonatomic, assign)NSInteger totalCount;
@property(nonatomic, strong)UILabel* placeLabel;
@property(nonatomic, strong)UILabel* countLabel;
@end

@implementation ZZFContentTextView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame withPlaceHolder:(NSString*)placeHolder withCount:(NSInteger)totalCount {
    if (self=[super initWithFrame:frame]) {
        _placeHolderStr=placeHolder;
        _totalCount=totalCount;
        [self configView];
    }
    return self;
}


#pragma mark -
#pragma mark <#statements#>
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    if (self.text.length == 0) {
        self.placeLabel.text = self.placeHolderStr;
    }else{
        self.placeLabel.text = @"";
    }
    
    NSString *toBeString = textView.text;
    NSString *lang = [textView.textInputMode primaryLanguage]; // 键盘输入模式
    if([lang isEqualToString:@"zh-Hans"] || [lang isEqualToString:@"zh-Hant"]) {
        UITextRange *selectedRange = [textView markedTextRange];
        //获取高亮部分sdf
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        //没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if(!position) {
            if(toBeString.length > self.totalCount) {
                textView.text = [self naturalStringFromString:toBeString limit:self.totalCount];
            }
        }
        //有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    //中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if(toBeString.length > self.totalCount) {
            textView.text = [self naturalStringFromString:toBeString limit:self.totalCount];
        }
    }
    
//    CGSize tmpSize=[self computeLineHeight:textView.text];
//    float numLine=ceilf(tmpSize.height/23);
    
//    [self.topView mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.height.mas_equalTo(numLine>1?54+(numLine-1)*23:54);
//    }];
    
    self.countLabel.text=[NSString stringWithFormat:@"%@/%@", @(textView.attributedText.length-[textView offsetFromPosition:textView.markedTextRange.start toPosition:textView.markedTextRange.end]), @(self.totalCount) ];
    self.text = textView.text;
    
}
- (NSString *)naturalStringFromString:(NSString *)srcString limit:(NSInteger)limit
{
    __block NSString * str = @"";
    [srcString enumerateSubstringsInRange:NSMakeRange(0, [srcString length])
                                  options:NSStringEnumerationByComposedCharacterSequences
                               usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
                                   if (str.length < limit && str.length + substring.length <= limit) {
                                       str = [str stringByAppendingString:substring];
                                   } else {
                                       *stop = YES;
                                   }
                               }];
    return str;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    if (textView.text.length < 1) {
        textView.text = @"间距";
    }
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineHeightMultiple = 1.5;// 字体的行间距
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:fontSize_12],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    
    textView.attributedText = [[NSAttributedString alloc] initWithString: textView.text attributes:attributes];
    
    if ([textView.text isEqualToString:@"间距"]) {
        textView.attributedText = [[NSAttributedString alloc] initWithString:@"" attributes:attributes];
    }
    return YES;
}

- (CGSize)computeLineHeight:(NSString*)tail{
    // label根据文字自适应高度
    UILabel *tailLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width-30, MAXFLOAT)];
    tailLabel.numberOfLines = 0;
    tailLabel.lineBreakMode = NSLineBreakByCharWrapping;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:tail];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:2.5];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [tail length])];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize_12] range:NSMakeRange(0, [tail length])];
    [tailLabel setAttributedText:attributedString];
    [tailLabel sizeToFit];
    return tailLabel.frame.size;
}


#pragma mark -
#pragma mark <#statements#>
- (void)configView {
    self.textColor = [UIColor colorWithHexString:colorHex_title_black];
    self.textAlignment = NSTextAlignmentLeft;
//    self.font = [UIFont systemFontOfSize:fontSize_12];
    self.backgroundColor = [UIColor greenColor];
    self.delegate = self;
    self.scrollEnabled = NO;
    self.keyboardType = UIKeyboardTypeDefault;
    self.textContainerInset = UIEdgeInsetsMake(10, 0, 0, 0);
    
    if (self.placeHolderStr.length>0) {
        [self addSubview:self.placeLabel];
        [self.placeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.mas_leading).offset(10);
            make.trailing.equalTo(self.mas_trailing).offset(0);
            make.top.equalTo(self);
            make.bottom.equalTo(self);
        }];
    }
    
    if (self.totalCount>0) {
        [self addSubview:self.countLabel];
        [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(self.mas_trailing).offset(-10);
            make.top.equalTo(self.mas_bottom);
            make.width.mas_equalTo(100);
            make.height.mas_equalTo(13);
        }];
    }
}

- (UILabel *)placeLabel{
    if (!_placeLabel) {
        _placeLabel= [[UILabel alloc] init];
        _placeLabel.backgroundColor=[UIColor orangeColor];
        _placeLabel.backgroundColor = [UIColor clearColor];
        _placeLabel.textAlignment = NSTextAlignmentLeft;
        _placeLabel.textColor = [UIColor colorWithHexString:colorHex_subtitle_gray_2];
        _placeLabel.font = [UIFont systemFontOfSize:fontSize_12];
        _placeLabel.text = self.placeHolderStr;
    }
    return _placeLabel;
}

- (UILabel*)countLabel {
    if (_countLabel == nil) {
        _countLabel=[UILabel new];
        _countLabel.backgroundColor=[UIColor purpleColor];
        _countLabel.text=[NSString stringWithFormat:@"0/%@", @(self.totalCount)];
        _countLabel.textColor=[UIColor colorWithHexString: colorHex_subtitle_gray_2];
        _countLabel.font=[UIFont systemFontOfSize:fontSize_11];
        _countLabel.textAlignment=NSTextAlignmentRight;
    }
    return _countLabel;
}

@end
